import React, {useState, useEffect} from 'react';
import PropTypes from 'prop-types';
import { Tree, Select, message } from 'antd';
import { Scrollbars } from 'react-custom-scrollbars';
import {centerOfMass, polygon} from '@turf/turf';
import axios from 'axios';
import memo from '../../common/wrapMemo';

import api from '../../../api/index';
import FeatureDetail from './FeatureDetail';

import style from './Layer.module.scss';
import LayerList from './LayerList';
import Loading from '../../common/Loading';
import {polygonColorMap} from '../../../constant/layers';
import JsonLoading from '../loading/Loading';
import LayerFilter from './LayerFilter';

const { Option } = Select;
const {L} = window; 
const {BASE_URL, WMS_URL, WMS_ID_MAP} = window.CONFIG;

let layerArrMap = {};

// 图层缓存数据
let catchLayerDatas = {};
// 图层渲染数据
let renderLayerDatas = {};
// 行政区划图层
let adminLayer = null;
// 行政区划子图层
let adminChildLayer = null;
// 筛选参数
let filterParams = {
    // shape: 1,           // 1:多边形，2：圆
    // radius: 100,        // 圆半径，单位：米
    // geojson: {}         // 多边形的空间信息
};
// 已选择图层keys
let selectedLayerKeys = [];
// 要素象形code值
let featureDetailCode = '';

let center = [];

// 面高亮图层
let polygonHighLayer = null;

// 面高亮样式配置
const highStyleOption = {
    weight: 2,
    opacity: 1,
    color: 'blue',
    fillOpacity: 0.2,
    fillColor: 'blue'
};

// 加载图层ids
let loadIds = [];
// code、layerName隐射表
let codeMapName = {};

const Layer = memo((props) => {
    const {map, setLayerShow, userInfo, layerFields, featureNames, treeData} = props;
    const fields = layerFields.toJS();

    const [cities, setCities] = useState([]);
    const [secondCity, setSecondCity] = useState([]);
    const [town, setTown] = useState('');
    const [village, setVillage] = useState('');

    const [layerListShow, setLayerListShow] = useState(false);              // 图层详情显隐
    const [featureDetailShow, setFeatureDetailShow] = useState(false);      // 要素详情显隐

    const [layerDatas, setLayerDatas] = useState([]); 
    const [featureDatas, setFeatureDatas] = useState({});                   // 要素详情数据
    const [curLayerName, setCurLayerName] = useState('');                   // 当前操作图层名称
    const [curLayerCode, setCurLayerCode] = useState('');                   // 当前操作图层code
    const [curUid, setCurUid] = useState(''); 
    
    const [expandedKeys, setExpandedKeys] = useState([]);
    const [selectedKeys, setSelectedKeys] = useState([]);
    const [autoExpandParent, setAutoExpandParent] = useState(true);
    const [areaUnits, setAreaUnits] = useState();
    const [visibleFields, setVisibleFields] = useState([]);

    const [treeDatas, setTreeDatas] = useState([]);                         // 图层列表树
    const [total, setTotal] = useState(0);
    const [pageInfo, setPageInfo] = useState({page: 1,size: 20});           // 分页信息                 
    
    const [treeLoading, setTreeLoading] = useState(false);
    const [layerLoading, setLayerLoading] = useState(false);
    const [featureLoading, setFeatureLoading] = useState(false);
    const [townLoading, setTownLoading] = useState(false);
    const [villageLoading, setVillageLoading] = useState(false);
    const [loadingIds, setLoadingIds] = useState([]);

    useEffect(() => {
        addRegionLayer();

        // 获取行政区划
        setTownLoading(true);
        const params = {
            code: '330225000000'
        };

        api.search.queryAdmin(params)
            .then(res => {
                const {code, data = []} = res.data;
                if(code === 200) {
                    const adminData = generateAdminData(data);
                    setCities(adminData);
                }
            }).catch(err => {
                console.log(err);
            }).finally(() => {
                setTownLoading(false);
            })

        return () => {
            if(map){
                removeLayers();
            }
            
            removeAdminLayer();
            removeAdminChildLayer();
            removeHighLayer();
            layerArrMap={};
            adminLayer = null;
            adminChildLayer = null;
        }
    },[]);

    // 注册地图点击事件
    useEffect(() => {
        if(!map) return;

        const clickEvent = (e) => {
            if(selectedLayerKeys.length === 0) return;

            const {latlng:{lat, lng}} = e;
            const geojson = {"type":"Point","coordinates":[lng,lat]};

            let keys = selectedLayerKeys.filter(key => {
                return Object.keys(WMS_ID_MAP).includes(String(key));
            });

            if(keys.length > 0) {
                const params = {
                    codes: keys.join(','),
                    geojson
                };
                api.layer.getWmsFeatureInfo(params)
                    .then(res => {
                        const {code, data} = res?.data;
                        if(code === 200) {
                            addWmsHighLayer(data);
                        }
                    })
            }
        };

        map.on('click', clickEvent);

        return (() => {
            map.off('click', clickEvent);
        });
    },[map]);

    useEffect(() => {
        setTreeLoading(true);
        if(treeData.length > 0){
            const data = generateTreeData(treeData);
            setTreeDatas(data);
            setTreeLoading(false);
        }
    },[treeData]);

    useEffect(() => {
        if(!featureDetailShow){
            removeHighLayer();
        }
    }, [featureDetailShow]);

    // 构造图层树数据
    const generateTreeData = (groups) => {
        let treeDatas = [];

        const recursive = (treeChildren, key, datas) => {
            datas.forEach((data) => {
                let childrenData = {}; 
                const {name, code, isClassify, fields} = data;
                codeMapName[code] = name;
                childrenData['title'] = name;
                childrenData['key'] = `${key}-${code}`;
                childrenData['code'] = code;
                childrenData['isClassify'] = isClassify;
                childrenData['fields'] = fields;
                if(data['children']){
                    childrenData['children'] = [];
                    recursive(childrenData.children, childrenData['key'], data['children']);
                }
                treeChildren.push(childrenData);
            });
        };

        recursive(treeDatas, 0, groups);

        return treeDatas;
    };

    // 组织行政区划数据
    const generateAdminData = (datas) => {
        const adminData = datas.map(data => {
            const {code, name} = data;
            return {
                label: code,
                value: name
            }
        });
        return adminData;
    };

    // 关闭图层管理面板
    const close = () => {
        setLayerShow(false);
    };

    // 乡镇切换事件
    const townChange = (val, option) => {
        setTown(val);
        setVillage('');
        setVillageLoading(true);
        const params = {
            code: val
        };

        api.search.queryAdmin(params).then((res) => {
            const {code, data} = res.data;
            if(code === 200) {
                const adminData = generateAdminData(data);
                setSecondCity(adminData);
            }
        }).catch((err) => {
            console.log(err);
        }).finally(() => {
            setVillageLoading(false);
        })

        // 添加镇、村图层
        addAdminLayer(option.key, "XZMC");
    };

    // 村切换事件
    const villageChange = (val, option) => {
        setVillage(val);
        // 添加镇、村图层
        addAdminLayer(option.key, "ZLDWMC");
    };

    // 添加镇、村图层
    const addAdminLayer = (val, name) => {
        // 移除镇、村图层
        removeAdminChildLayer();

        let url = `${WMS_URL}/geoserver/xsxfarm/wms`;
        const layer = 'xsfarm:admin';
 
        const params = {
            service:'WFS',
            version:'1.1.0',
            request:'GetFeature',
            typeName:layer,
            outputFormat:'application/json',
            srsName:'EPSG:4326',
            CQL_FILTER:`${name} = '${val}'`
        };

        const url_str = url + L.Util.getParamString(params,url)
       
        axios({
            method: 'get', 
            url:url_str,
            responseType:'json'
        }).then(res=>{
            if(res.data) {
                adminChildLayer = L.geoJson(res.data,{
                    style: {
                        "color": "red",
                        "weight": 2,
                        "opacity": 0.8,
                        "fillOpacity": 0
                    }
                });
                adminChildLayer.addTo(map);
                map.fitBounds(adminChildLayer.getBounds());
            }
        })
    };

    // 移除行政区划图层
    const removeAdminLayer = () => {
        if(map && adminLayer){
            map.removeLayer(adminLayer);
            adminLayer = null;
        }
    };

    // 移除镇、村图层
    const removeAdminChildLayer = () => {
        if(map && adminChildLayer){
            map.removeLayer(adminChildLayer);
            adminChildLayer = null;
        }
    };

    // 添加行政区划图层
    const addRegionLayer = () => {
        if(!map) return;
        // adminLayer = L.tileLayer.wms(
        //     `${WMS_URL}/xsfarm/wms?`,
        //     {
        //         layers: "xsfarm:admin", //需要加载的图层
        //         format: "image/png", //返回的数据格式
        //         transparent: true,
        //     }).addTo(map);

        adminLayer = L.tileLayer.wms(`${WMS_URL}/geoserver/xsxfarm/wms?`, {
            layers: `xsxfarm:admin`,     
            format: "image/png",    
            transparent: true,
        }).addTo(map);


        // adminLayer = L.tileLayer(`${WMS_URL}/geoserver/xsxfarm/wms?layer=xsxfarm:admin&style=&tilematrixset=EPSG:900913&Service=WMS&Request=GetMap&Version=1.0.0&Format=image/png&TileMatrix=EPSG:900913:{z}&TileCol={x}&TileRow={y}`, {
        //         minZoom: 2,
        //         maxZoom: 18,
        //     }).addTo(map);

        // map.fitBounds(adminLayer.getBounds());
    };

    // 获取要素详情信息
    const getFeatureDetail = (uid, code='') => {
        setFeatureDetailShow(true);
        setFeatureLoading(true);
        setCurUid(uid);
        const layerCode = code? code : curLayerCode;

        if(code){
            setCurLayerCode(String(code));
        }

        // 获取图斑详情
        const params = {
            uid,
            code: layerCode
        };
        // 获取面积单位
        getUnits(Number(layerCode));
        featureDetailCode = code;
        removeHighLayer();
        api.search.queryFeatureInfo(params)
            .then(res => {
                const {code, data} = res.data;
                if(code === 200){
                    const {geojson, ...resetData} = data;
                    const geojsonData = JSON.parse(geojson);
                    if(geojsonData){
                        const {type, coordinates} = geojsonData;
                        const featureType = getType(type);
                        if(featureType === 'point'){
                            center = coordinates;
                            polygonHighLayer = L.circle([center[1], center[0]], {radius: 10}).addTo(map);
                        }
                        if(featureType === 'polygon'){
                            const pointJson = centerOfMass(polygon(geojsonData['coordinates']));
                            center = pointJson.geometry.coordinates;
                            polygonHighLayer = L.geoJSON(geojsonData, highStyleOption).addTo(map);
                        }
                        if(featureType === 'MultiPolygon'){
                            const pointJson = centerOfMass(polygon(geojsonData['coordinates'][0]));
                            center = pointJson.geometry.coordinates;
                            polygonHighLayer = L.geoJSON(geojsonData, highStyleOption).addTo(map);
                        }
                    }
                    featureLocation();
                    setFeatureDatas(resetData);
                }
            }).catch(err => {
                console.log(err);
            }).finally(() => {
                setFeatureLoading(false);
            })
    };

    // 重置
    const reset = () => {
        setTown('');
        setVillage('');
        removeAdminChildLayer();
        if(map && adminLayer){
            // map.fitBounds(adminLayer.getBounds());
        }
    }; 

    // 获取面积单位
    const getUnits = (num) => {
        let areaUnits = {};
        let visibleFields = [];

        const cycle = (datas) => {
            datas.forEach(data => {
                const {code, children, fields} = data;
                if(code === num){
                    const {units={}, visible=''} = fields;
                    areaUnits = units;
                    visibleFields = visible.split(',');
                }else{
                    if(children.length > 0){
                        cycle(children);
                    }
                }
            })
        }

        cycle(treeData);
        setAreaUnits(areaUnits);
        setVisibleFields(visibleFields);
    };

    // 删除要素
    const deleteFeature = (uid=curUid, code=curLayerCode) => {
        const params = {
            code, 
            uid
        };

        api.search.deleteFeature(params)
        .then(res => {
            const {code} = res.data;
            if(code === 200){
                setFeatureDetailShow(false);
                message.success('图斑删除成功！');
                getLayerList();
            }else{
                message.error('图斑删除失败！');
            }
        }).catch(err => {
            console.log(err);
            message.error('图斑删除失败！');
        });
        
    };

    // 保存编辑要素
    const saveFeature = (val) => {
        const params = {
            operationContent:{
                items:{...val},
                itemsPrev:{},
                operation: 'update',
                uid: curUid
            },
            operationLayer: curLayerCode? curLayerCode : ''
        };

        console.log(curLayerName);

        api.search.saveFeature(params)
            .then(res => {
                const {code} = res.data;
                if(code === 200) {
                    message.success('提交成功！');
                    getLayerList();
                    setFeatureDetailShow(false);
                }else{
                    message.error('提交失败！');
                }
            }).catch(() => {
                message.error('提交失败！');
            });
    };

    // 要素定位
    const featureLocation = () => {
        // if(map && center[0] && center[1]){
        //     map.setView([center[1], center[0]]);
        // }

        if(map && polygonHighLayer){
            map.fitBounds(polygonHighLayer.getBounds());
        }
    };

    // 关闭图层列表面板
    const closeLayerListPanel = () => {
        setLayerListShow(false);
        setFeatureDetailShow(false);
    };

    const onExpand = (expandedKeysValue) => {
        setExpandedKeys(expandedKeysValue);
        setAutoExpandParent(false);
    };

    const onCheck = (checkedKeysValue,e) => {
        const {checkedNodes=[]} = e;

        let codes = [];
        checkedNodes.forEach(node => {
            if(!node['children'] || node['children'].length === 0){
                const {code} = node;
                codes.push(code);
            }
        });

        if(featureDetailCode && !codes.includes(featureDetailCode)){
            setFeatureDetailShow(false);
            removeHighLayer();
        }

        selectedLayerKeys = codes;
        addOrRemoveLayer(codes);
    };

    // 删除或添加图层
    const addOrRemoveLayer = (checkKeys) => {
        const existLayerKeys = Object.keys(renderLayerDatas);

        // 移除
        existLayerKeys.forEach(key => {
            const isRemove = checkKeys.find(item => {
                return String(item) === key;
            });

            if(!isRemove){
                // 删除图层并将layerDatas中对应的数据删除
                if(layerArrMap[key]){
                    layerArrMap[key].forEach(item => {
                        renderLayerDatas[key] && renderLayerDatas[key].layer.resetStyle(item);
                    });
                }
                map.removeLayer(renderLayerDatas[key].layer);
                delete renderLayerDatas[key];
            }
        });

        // 新增
        checkKeys.forEach(key => {
            // renderLayerDatas中不存在的为新增
            const isExist = Object.keys(renderLayerDatas).find(item => {
                return item === key;
            });

            if(!isExist){
                // catchLayerDatas中存在
                if(catchLayerDatas[key]){
                    renderLayerDatas[key] = catchLayerDatas[key];
                    // 添加图层
                    map.addLayer(renderLayerDatas[key].layer);
                }else{
                    // 判断是否为wms图层
                    if(Object.keys(WMS_ID_MAP).includes(String(key))){
                        addWmsLayer(key, WMS_ID_MAP[key]);
                    }else{
                        // 请求数据
                        getJsonData(key);
                    }
                }
            }
        })
    };

    // 添加wms服务图层
    const addWmsLayer = (key, name) => {
        let params = {
            layers: `xsxfarm:${name}`,      
            format: "image/png",             
            transparent: true,               
        };

        const { szxz = '' } = userInfo.toJS();

        let cqlFilters = [];

        if(szxz){
            cqlFilters.push(`szxz = '${szxz}'`);
        }

        if(Object.keys(filterParams).length > 0){
            const {shape, radius, geojson: {coordinates}} = filterParams;
            if(shape === 1){
                const polyData = getPoly(coordinates[0]);
                // params['CQL_FILTER'] = `INTERSECTS(geom, POLYGON((${polyData})))`;
                cqlFilters.push(`INTERSECTS(geom, POLYGON((${polyData})))`);
            }else{
                // params['CQL_FILTER'] = `INTERSECTS(geom, BUFFER(POINT(${coordinates[0]} ${coordinates[1]}), ${radius/100000}))`;
                cqlFilters.push(`INTERSECTS(geom, BUFFER(POINT(${coordinates[0]} ${coordinates[1]}), ${radius/100000}))`);
            }
        }

        if(cqlFilters.length > 0){
            params['CQL_FILTER'] = cqlFilters;
        }

        const layer = L.tileLayer.wms(`${WMS_URL}/geoserver/xsxfarm/wms?`, params);
        
        map.addLayer(layer);
        const combineData = {type:'polygon', layer};
        renderLayerDatas[key] = combineData;
        catchLayerDatas[key] = combineData;
        return layer;
    };

    // 添加wms服务高亮图层
    const addWmsHighLayer = (data) => {
        removeHighLayer();

        const keys = Object.keys(data);
        let code = '';
        if(keys.length > 0){
            code = keys[keys.length - 1];
            const {geojson, uid} = data[code];
            const jsonData = JSON.parse(geojson);

            polygonHighLayer = L.geoJSON(jsonData, highStyleOption).addTo(map);
            getFeatureDetail(uid, code);
        }
    };

    // 移除高亮
    const removeHighLayer = () => {
        
        // 移除高亮图层
        if(polygonHighLayer && map){
            map.removeLayer(polygonHighLayer);
            polygonHighLayer = null;
        }

        // 移除geojson高亮
        Object.keys(layerArrMap).forEach(key => {
            layerArrMap[key].forEach(item => {
                renderLayerDatas[key] && renderLayerDatas[key].layer.resetStyle(item);
            });
        });
    };

    // cql_filter 参数获取
    const getPoly = (datas) => {
        let poly = [];

        datas.forEach(data => {
            if(Array.isArray(data)){
                const item = `${data[0]} ${data[1]}`;
                poly.push(item);
            }
        });

        return poly.join(',');
    }

    // 获取图斑json数据
    const getJsonData = (key) => {
        loadIds = [...loadIds, key];
        setLoadingIds(loadIds);
        const params = {
            code: key,
            regionCode: village? village : town ? town : '',
            ...filterParams
        };

        api.search.queryLayerJson(params)
            .then((res) => {
                const {code, data} = res.data;
                if(code === 200){
                    const {type, jsonData} = getGeojsonData(data, key);
                    const layer = addOverLayer({type, jsonData}, key);
                    const combineData = {type, jsonData, layer};
                    renderLayerDatas[key] = combineData;
                    catchLayerDatas[key] = combineData;
                }
            }).catch((err) => {
                console.log(err);
            }).finally(() => {
                const ids = JSON.parse(JSON.stringify(loadIds));
                const index = ids.findIndex(item => {
                    return item === key;
                });
                if(index !== -1){
                    ids.splice(index, 1);
                    loadIds = ids;
                    setLoadingIds(loadIds);
                }
            })
    };

    // 添加覆盖物图层
    const addOverLayer = (overLayerData, code) => {
        const {type, jsonData} = overLayerData;
        let layer = null;
        
        if(type === 'point'){
            let pointIcon = L.icon({
                iconUrl: `${BASE_URL}/images/${code}.png`,
                iconSize:[26,26],
                // iconAnchor: [12,12]
            });
        
            window.pointLayer = layer = L.geoJSON(jsonData, {   
                pointToLayer: function (feature, latlng){
                    return L.marker(latlng, {
                        icon: pointIcon
                    });
                },
                onEachFeature: ((feature, layer) => { 
                    layer.on({
                        click: ((e) => {
                            // 要素详情展示
                            const {properties:{code, uid}} = e.target.feature;
                            getFeatureDetail(uid, code);
                        })
                    });
                })
            });
        }
     
        if(type === 'polygon' || type === 'MultiPolygon'){
            let polygonOptions = {  
                color: polygonColorMap[code] ? polygonColorMap[code] : 'red',
                weight: 2,
                opacity: 1,
                fillColor: polygonColorMap[code] ? polygonColorMap[code] : 'red',
                fillOpacity: 0.6
            };
            layerArrMap[code] = [];
            layer = L.geoJSON(jsonData, {   
                style: polygonOptions,
                onEachFeature: ((feature, layer) => { //对每个小块进行定义
                    layerArrMap[code].push(layer);
                    layer.on({
                        //点击方法，变色
                        click: ((e) => {
                            var layer = e.target;
                            // 要素详情展示
                            const {properties:{code, uid}} = e.target.feature;
                            layer.setStyle(highStyleOption);
                            getFeatureDetail(uid, code);
                        })
                    });
                })
            });
        }

        map.addLayer(layer);
        return layer;
    }

    // 获取geojson数据
    const getGeojsonData = (datas, code) => {
        let features = [];
        let jsonType = 'point';
        datas.forEach((data, index) => {
            const {uid} = data;
            if(data.geojson){
                const geojson = JSON.parse(data.geojson);
                if(Object.keys(geojson).length > 0 && uid){
                    const feature = {
                        "type": "Feature",
                        "geometry": geojson,
                        "properties": {
                            "code": code,
                            "uid": uid
                        },
                    };
                    features.push(feature);
        
                    if(index === 0){
                        jsonType = getType(geojson.type);
                    }
                }
            }
        });

        let geojsonData = {
            "type": "FeatureCollection",
            "crs": {"type": "name", "properties": {"name": "EPSG:4490"}},
            "features": features
        };

        return {
            type: jsonType,
            jsonData: geojsonData
        }
    };

    // 获取要素类型
    const getType = (jsonType) => {
        const type = jsonType.toLocaleLowerCase();
        if(type.includes('point')){
            return 'point';
        }

        if(type.includes('line')){
            return 'line';
        }

        if(type.startsWith('polygon')){
            return 'polygon';
        }

        if(type.startsWith('multipolygon')){
            return 'MultiPolygon';
        }
    };

    // 自定义图形绘制结束事件
    const drawEnd = (val) => {
        filterParams = val;

        if(selectedLayerKeys.length === 0 || !map) return;

        removeLayers();

        addOrRemoveLayer(selectedLayerKeys);
        // 获取要素列表
        if(selectedLayerKeys[0]){
            const code = selectedLayerKeys[0];
            const layerName = codeMapName[code] || '';
            const pages = {
                page: 1,
                size: 20
            };
            getLayerList(code, layerName, pages);
        }
    };

    // 移除图层
    const removeLayers = () => {
        Object.keys(renderLayerDatas).forEach(key => {
            renderLayerDatas[key].layer && map.removeLayer(renderLayerDatas[key].layer);
        });
        renderLayerDatas = {};
        catchLayerDatas = {};
    }

    // 图层点击事件
    const onSelect = (selectedKeysValue, info) => {
        const pageInfo = {page: 1,size: 20}
        setPageInfo(pageInfo);
        setSelectedKeys(selectedKeysValue);
        if(info.node.children.length > 0) return;

        getLayerList(info.node.code, info.node.title, pageInfo);
    };

    // 页码变化事件
    const pageChange = (pages) => {
        setPageInfo(pages);
        getLayerList('','', pages);
    };

    // 获取选中图层要素列表
    const getLayerList = (code, layerName, page={}) => {
        code = code ? code : curLayerCode;
        layerName = layerName? layerName : curLayerName;

        if(!code || !layerName) return;

        setLayerListShow(true);
        setLayerLoading(true);
        setCurLayerName(layerName);
        setCurLayerCode(String(code));

        const params = {
            code,
            regionCode: village? village : town ? town : '',
            ...filterParams,
            pageParam: {
                ...pageInfo,
                ...page
            }
        };

        api.search.queryLayerList(params)
            .then((res) => {
                const {code, data} = res.data;
                if(code === 200){
                    const {count, result} = data;
                    setTotal(count);
                    setLayerDatas(result);
                }
            }).catch(err => {
                console.log(err);
            }).finally(() => {
                setLayerLoading(false);
            })
    };

    // 乡镇数据options
    const getCityOptions = cities.map(city => {
        return <Option value={city.label} key={city.value}>{city.value}</Option>
    });

    // 村数据options
    const getSecondCityOptions = secondCity.map(city => {
        return <Option value={city.label} key={city.value}>{city.value}</Option>
    });

    const filedNames = {
        title: 'name',
    };

    return (
        <>
            <div className={style.layerTree}>
                <div className={style.header}>
                    <span>图层管理</span>
                    <i className="iconfont icon-close" onClick={close}></i>
                </div>
                <div className={style.region}>
                    <div className={style.title}>地区</div>
                    <div className={style.content}>
                        <Select placeholder="请选择镇" style={{ width: 128, marginRight: 8 }} onChange={townChange} value={town} loading={townLoading}>
                            {getCityOptions}
                        </Select>
                        <Select placeholder="请选择村" style={{ width: 128 }}  onChange={villageChange} value={village} loading={villageLoading}>
                            {getSecondCityOptions}
                        </Select>
                        <span className={style.reset} onClick={reset}>重置</span>
                    </div>
                </div>
                <LayerFilter 
                    map={map} 
                    drawEnd={drawEnd}/>
                <div className={style.tree}>
                    <div className={style.header}>
                        <span>图层列表</span>
                    </div>    
                    <div className={style.separate}></div>
                    <div className={style.content}>
                        {
                            treeLoading ? <Loading />: 
                            <Scrollbars autoHeight autoHeightMin={0} autoHeightMax={`calc(100vh - 393px)`}>
                                <Tree
                                    checkable
                                    onExpand={onExpand}
                                    expandedKeys={expandedKeys}
                                    autoExpandParent={autoExpandParent}
                                    onCheck={onCheck}
                                    onSelect={onSelect}
                                    selectedKeys={selectedKeys}
                                    treeData={treeDatas}
                                    fieldNames={filedNames}/>
                            </Scrollbars>
                        }
                    </div>       
                </div>
            </div> 
            {
                layerListShow && curLayerCode &&
                    <LayerList 
                        left={384}
                        total={total}
                        pageInfo={pageInfo}
                        pageChange={pageChange}
                        setPageInfo={setPageInfo}
                        layerDatas={layerDatas}
                        featureNames={featureNames}
                        curLayerCode={curLayerCode}
                        loading={layerLoading}
                        getFeatureDetail={getFeatureDetail}
                        closeLayerListPanel={closeLayerListPanel}/>
            }
            {
                featureDetailShow &&
                    <FeatureDetail 
                        userInfo={userInfo}
                        layerFields={layerFields}
                        featureDatas={featureDatas}
                        fields={fields}
                        visibleFields={visibleFields}
                        areaUnits={areaUnits}
                        featureLoading={featureLoading}
                        deleteFeature={deleteFeature}
                        featureLocation={featureLocation}
                        saveFeature={saveFeature}
                        setFeatureDetailShow={setFeatureDetailShow}/>
            }
            {
                loadingIds.length > 0 && <JsonLoading />
            }
        </>
    )
});

Layer.propTypes = {
    map: PropTypes.object,
    userInfo: PropTypes.object,
    setLayerShow: PropTypes.func,
    layerFields: PropTypes.object,
    featureNames: PropTypes.object,
};

export default Layer;